import {fnAddDynamicMenuRoutes} from '@/api/getAsyncRouter'
import { getRouters } from '@/api/getCurrentUserMenu'
import { getCookie, setCookie, removeCookie, storage, session } from '@/utils/auth'
import {constantRoutes} from '@/router/constantRoutes'

const getDefaultState = () => {

    return {
        routes: constantRoutes,
        addRoutes:[],
        isRouters:false
    }

}
const state = getDefaultState()

const mutations = {
    SET_ROUTES: (state, routes) => {
        // console.log(routes);
        // console.log(constantRoutes);
        state.addRoutes = routes
        state.routes = constantRoutes.concat(routes)
        //路由加载好将标识设为true
        state.isRouters = true
        // console.log(constantRoutes);
    },
    RESET_STATE: (state) => {
        Object.assign(state, getDefaultState())
    },
}

const actions = {
    generateRouter({commit},userId){
        return new Promise( resolve =>{
            getRouters( {userId : userId} ).then( res => {

                if(res.data.data.length <= 0){
                    return 
                }
                const menuRouter = fnAddDynamicMenuRoutes(res.data.data[0].children)
                // console.log(menuRouter);
                commit('SET_ROUTES',menuRouter)
                resolve(menuRouter)
            })
        })
    },
    removeRouter({ commit }) {
        return new Promise(resolve => {
            commit('RESET_STATE')
            session.clear()
            resolve()
        })
    }
}

export default {

    namespaced: true,
    state,
    mutations,
    actions,
}
